// axios 简单封装
import axios from 'axios';

import { CODE_LOGGED_OTHER, CODE_RELOGIN } from '../config/status-code';
import { ACCESS_TOKEN, AUTH } from '../config/constants';
import router from '../router/index'

const server = axios.create({
  baseURL: '//127.0.0.1:4000',
  timeout: 30000
});

const API = {};

API.getLogin = (params) => {
  return server.get('/login', { params: params });
}

API.getData = () => {
  return server.get('/getData');
}

// 接口权限
// 请求拦截，在请求头加入 Authorization 字段，加入 token
server.interceptors.request.use((config) => {
  let { headers } = config;
  const tk = localStorage.getItem(ACCESS_TOKEN);
  if (tk) {
    Object.assign(headers, {
      [AUTH]: tk,
    });
  }
  return config;
}, (error) => {
  return Promise.reject(error);
})

// 响应拦截
// 返回状态码为106或104时，路由到登录页面，同时返回res
server.interceptors.response.use((res) => {
  let { data } = res;
  if (
    data.returncode == CODE_LOGGED_OTHER ||
    data.returncode == CODE_RELOGIN
  ) {
    router.push('/login');
    location.reload();
  }
  return res;
}, (error) => {
  return Promise.reject(error);
})

export default API;